package camuyen.ltwlibrary.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.annotations.common.util.impl.LoggerFactory;
import org.jboss.logging.Logger;

import camuyen.ltwlibrary.dao.UserDao;
import camuyen.ltwlibrary.model.User;

/**
 * Servlet implementation class AuthorizerServlet
 */
public class AuthorizerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthorizerServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username").toLowerCase();
		String password = request.getParameter("password");
		
		HttpSession session = request.getSession();
		boolean isLoggedIn = login(username, password);
		if(isLoggedIn) {
			User loggedInUser = UserDao.getUserByUsername(username);
			session.setAttribute("isLoggedIn", true);
			session.setAttribute("loggedInUser", loggedInUser);
			response.sendRedirect("index.jsp");
		} else {
			session.setAttribute("loginMessage", "Username or password is not correct.");
			response.sendRedirect("index.jsp");
		}
	}

	private boolean login(String username, String password) {
		User user = UserDao.getUserByUsername(username);
		if (user != null && user.getPassword().equals(password)) {
			return true;
		}
		return false;
	}
}
